<template>
    <!--地图挂载dom-->
    <div id="map">
    </div>
</template>

<script>
    //引入依赖
    import {Map, View} from 'ol'
    import {OSM, Vector as VectorSource} from 'ol/source'
    import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
    import {GeoJSON} from 'ol/format';
    import {jsPDF} from "jspdf";

    export default {
        name: 'ProjectExportPDF',
        data() {
            return {
                map: null,
                format:'a4',
                resolution:'72',
                dims :{
                    a0: [1189, 841],
                    a1: [841, 594],
                    a2: [594, 420],
                    a3: [420, 297],
                    a4: [297, 210],
                    a5: [210, 148],
                }
            }
        },
        mounted() {

            this.osm = new TileLayer({
                source: new OSM(),
            });
            this.map = new Map({
                target: 'map',//指定挂载dom，注意必须是id
                layers: [
                    this.osm
                ],
                //配置视图
                view: new View({
                    center: [ 113.09051513671875, 22.864154522619437],   //视图中心位置
                    projection: "EPSG:4326", //指定投影
                    zoom: 10   //缩放到的级别
                })
            });


            let geojson={
                "type": "FeatureCollection",
                "features": [
                    {
                        "type": "Feature",
                        "properties": {},
                        "geometry": {
                            "type": "Polygon",
                            "coordinates": [
                                [
                                    [
                                        113.09051513671875,
                                        22.864154522619437
                                    ],
                                    [
                                        113.46885681152344,
                                        22.864154522619437
                                    ],
                                    [
                                        113.46885681152344,
                                        23.132151518752178
                                    ],
                                    [
                                        113.09051513671875,
                                        23.132151518752178
                                    ],
                                    [
                                        113.09051513671875,
                                        22.864154522619437
                                    ]
                                ]
                            ]
                        }
                    }
                ]
            };
            let geoJSON = new GeoJSON();
            let features = geoJSON.readFeatures(geojson);
            let vector = new VectorSource();
            let layer = new VectorLayer({
                source: vector
            });
            vector.addFeatures(features);
            this.map.addLayer(layer);

            //5秒之后导出地图
            setTimeout(()=>{
                this.exportPDF();
            },5000)
        },
        methods: {

            exportPDF(){
                const dim = this.dims[this.format];
                //根据使用的纸张的高宽计算绘制范围宽高
                const width = Math.round((dim[0] * this.resolution) / 25.4);
                const height = Math.round((dim[1] * this.resolution) / 25.4);
                const size = this.map.getSize();
                const viewResolution = this.map.getView().getResolution();
                //监听渲染完成的事件，只监听一次
                this.map.once('rendercomplete',  ()=> {
                    //单独创建了canvas
                    const mapCanvas = document.createElement('canvas');
                    mapCanvas.width = width;
                    mapCanvas.height = height;
                    //获取到canvas的上下文对象
                    const mapContext = mapCanvas.getContext('2d');
                    Array.prototype.forEach.call(
                        //获取到当前绘制的openlayers绘制图层的canvas
                        document.querySelectorAll('.ol-layer canvas'),
                        function (canvas) {
                            if (canvas.width > 0) {
                                //获取到canvas的透明度
                                const opacity = canvas.parentNode.style.opacity;
                                //地图有透明度就把地图透明度给等待绘制的canvas社会透明度
                                mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
                                //获取到canvas的矩阵
                                const transform = canvas.style.transform;
                                // Get the transform parameters from the style's transform matrix
                                const matrix = transform
                                    .match(/^matrix\(([^\(]*)\)$/)[1]
                                    .split(',')
                                    .map(Number);
                                console.log(matrix);
                                // Apply the transform to the export map context
                                //给等待绘制的canvas设置地图的矩阵
                                CanvasRenderingContext2D.prototype.setTransform.apply(
                                    mapContext,
                                    matrix
                                );
                                //再绘制地图给canvas
                                mapContext.drawImage(canvas, 0, 0);
                            }
                        }
                    );
                   // mapContext.globalAlpha = 1;
                    //构建pdf组件
                    const pdf = new jsPDF('landscape', undefined, this.format);
                    //将绘制的canvas地图服PDF组件，并且需要传入尺寸
                    pdf.addImage(
                        mapCanvas.toDataURL('image/jpeg'),
                        'JPEG',
                        0,
                        0,
                        dim[0],
                        dim[1]
                    );
                    //pdf保存并设置pdf文件的名称
                    pdf.save('map.pdf');
                    // 重置地图的尺寸和分辨率
                    this.map.setSize(size);
                    this.map.getView().setResolution(viewResolution);
                });

                // 设置尺寸
                const printSize = [width, height];
                this.map.setSize(printSize);
                const scaling = Math.min(width / size[0], height / size[1]);
                this.map.getView().setResolution(viewResolution / scaling);
            }
        }
    }
</script>

<style scoped>
    #map {
        width: 100%;
        height: 100%;
    }
</style>
